import React, {
    useState,
    useMemo,
    useEffect
} from "react";
import fetch from "@/util/fetch";
import $ from "jquery";
import "./index.scss";
import { Loading } from "../../../component/common";

const _sysId = 410;

/**
 * type: user(用户), grade(年级), class(班级), group(教师/教研组), identity(管理员身份), org(部门)
 * groupType: admin(管理员), tea(教师), stu(学生), parent(家长), org(部门)
 * 
 */
function GroupList(props){
    let {
        groupData,
        selectList,
        selectMethod
    } = props;
    const [childList, setChildList] = useState([]);
    const [updateChildList, setUpdateChildList] = useState([]);
    const [getAll, setGetAll] = useState(false);
    const [childVisible, setChildVisible] = useState(false);
    const [loadVisible, setLoadVisible] = useState(false);
    const selectIdList = useMemo(()=>{
        let list = [];
        //不仅仅要id相同，还得分类相同，比如学生和家长都存在年级、班级选项
        Array.isArray(selectList) &&
        selectList.forEach((item)=>{
            list.push((item.groupType? item.groupType + "_": "") + item.id);
        })
        return list;
    }, [selectList]);
    const [showChild, setShowChild] = useState(false);
    const [historyList, setHistoryList] = useState([
        {
            id: "",
            name: groupData.name
        }
    ]);
    const [allChildList, setAllChildList] = useState([]);
    const [selectAll, setSelectAll] = useState(0);
    //获取子列表
    const getChildList = (data, type, e) => {
        //根据type判断点击的是哪一层，然后调用相应的接口
        //并且将当前点击的分组放入历史点击数组中
        if(!data.type || data.type === "user"){
            return;
        }
        e && e.preventDefault();
        e && e.stopPropagation();
        let history = JSON.parse(JSON.stringify(historyList));
        let allChild = JSON.parse(JSON.stringify(allChildList));
        let dataId = (data.groupType? data.groupType + "_": "") + data.id
        setLoadVisible(true);
        if(data.type === "grade"){  //如果是年级，获取年级下所有班级
            let url = window.BasicProxy + "/api/commons/school/class/list";
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                schoolId: sessionStorage.getItem("schoolId"),
                sysId: _sysId,
                gradeId: data.id,
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.classId,
                            groupType: data.groupType,
                            type: "class",
                            // parentId: dataId,
                            name: item.className
                        }
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            });
        }
        if(data.type === "class"){  //如果是班级则获取学生/家长
            let url = "";
            if(groupData.id === "stu"){
                url = window.BasicProxy + "/api/commons/school/user/students";
            } else {
                url = window.BasicProxy + "/api/commons/school/user/parents";
            }
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                classId: data.id
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.userId,
                            name: item.userName,
                            // parentId: dataId,
                            groupType: data.groupType,
                            type: "user"
                        }
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            });
        }
        if(data.type === "group"){  //如果是教研组获取教师列表
            let url = window.BasicProxy + "/api/commons/school/user/teachers";
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                groupId: data.id
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.userId,
                            name: item.userName,
                            // parentId: dataId,
                            groupType: data.groupType,
                            type: "user"
                        }
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            });
        }
        if(data.type === "identity"){
            let url = window.BasicProxy + "/api/commons/school/user/identity";
            fetch
            .get({url, params: {
                schoolId: sessionStorage.getItem("schoolId"),
                identityCode: data.id
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.userId,
                            name: item.userName,
                            // parentId: dataId,
                            groupType: data.groupType,
                            type: "user"
                        }
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            });
        }
        if(data.type === "org"){
            if(data.childCount !== "0"){  //如果有子部门，则显示子部门
                let url = window.BasicProxy + "/api/commons/school/department/list";
                fetch
                .get({url, params: {
                    sysId: "410",
                    schoolId: sessionStorage.getItem("schoolId"),
                    departmentId: data.id
                }})
                .then(res=>res.json())
                .then((result)=>{
                    if(result.code === "200" && Array.isArray(result.data)){
                        let updateList = result.data.map((item)=>{
                            return {
                                ...item,
                                id: item.departmentId,
                                name: item.departmentName,
                                parentId: dataId,
                                groupType: data.groupType,
                                type: "org"
                            }
                        })
                        url = window.BasicProxy + "/api/commons/school/user/department/staffs";
                        fetch
                        .get({url, params: {
                            sysId: "410",
                            schoolId: sessionStorage.getItem("schoolId"),
                            departmentId: data.id
                        }})
                        .then(res=>res.json())
                        .then((result)=>{
                            if(result.code === "200" && Array.isArray(result.data)){
                                let updateList2 = result.data.map((item)=>{
                                    return {
                                        ...item,
                                        id: item.userId,
                                        name: item.userName,
                                        parentId: dataId,
                                        groupType: data.groupType,
                                        type: "user"
                                    }
                                })
                                let allList = updateList.concat(updateList2);
                                setChildList(allList);
                                setLoadVisible(false);
                            }
                        });
                        // setChildList(updateList);
                        // setLoadVisible(false);
                    }
                });
            } else {
                let url = window.BasicProxy + "/api/commons/school/user/department/staffs";
                fetch
                .get({url, params: {
                    sysId: "410",
                    schoolId: sessionStorage.getItem("schoolId"),
                    departmentId: data.id
                }})
                .then(res=>res.json())
                .then((result)=>{
                    if(result.code === "200" && Array.isArray(result.data)){
                        let updateList = result.data.map((item)=>{
                            return {
                                ...item,
                                id: item.userId,
                                parentId: dataId,
                                name: item.userName,
                                type: "user"
                            }
                        })
                        setChildList(updateList);
                        setLoadVisible(false);
                    }
                });
            }
            
            
        }
        if(type !== "historyClick"){
            history.push(data);
            setHistoryList(history);
        }
    }
    //清除子选项
    const clearChildList = (data) => {
        //根据type判断点击的是哪一层，然后调用相应的接口
        //并且将当前点击的分组放入历史点击数组中
        if(!data.type || data.type === "user"){
            return;
        }
        let dataId = (data.groupType? data.groupType + "_": "") + data.id;
        if(data.type === "grade"){  //如果是年级，获取年级下所有班级
            let url = window.BasicProxy + "/api/commons/school/class/list";
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                schoolId: sessionStorage.getItem("schoolId"),
                sysId: _sysId,
                gradeId: data.id,
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.classId,
                            groupType: data.groupType,
                            type: "class",
                            // parentId: dataId,
                            name: item.className
                        }
                    })
                    clearMethod(data, updateList);
                }
            });
        }
        if(data.type === "class"){  //如果是班级则获取学生/家长
            let url = "";
            if(groupData.id === "stu"){
                url = window.BasicProxy + "/api/commons/school/user/students";
            } else {
                url = window.BasicProxy + "/api/commons/school/user/parents";
            }
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                classId: data.id
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.userId,
                            name: item.userName,
                            // parentId: dataId,
                            groupType: data.groupType,
                            type: "user"
                        }
                    })
                    clearMethod(data, updateList);
                }
            });
        }
        if(data.type === "group"){  //如果是教研组获取教师列表
            let url = window.BasicProxy + "/api/commons/school/user/teachers";
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                groupId: data.id
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.userId,
                            name: item.userName,
                            // parentId: dataId,
                            groupType: data.groupType,
                            type: "user"
                        }
                    })
                    clearMethod(data, updateList);
                }
            });
        }
        if(data.type === "identity"){
            let url = window.BasicProxy + "/api/commons/school/user/identity";
            fetch
            .get({url, params: {
                schoolId: sessionStorage.getItem("schoolId"),
                identityCode: data.id
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.userId,
                            name: item.userName,
                            // parentId: dataId,
                            groupType: data.groupType,
                            type: "user"
                        }
                    })
                    clearMethod(data, updateList);
                }
            });
        }
        if(data.type === "org"){
            if(data.childCount !== "0"){  //如果有子部门，则显示子部门
                let url = window.BasicProxy + "/api/commons/school/department/list";
                fetch
                .get({url, params: {
                    sysId: "410",
                    schoolId: sessionStorage.getItem("schoolId"),
                    departmentId: data.id
                }})
                .then(res=>res.json())
                .then((result)=>{
                    if(result.code === "200" && Array.isArray(result.data)){
                        let updateList = result.data.map((item)=>{
                            return {
                                ...item,
                                id: item.departmentId,
                                name: item.departmentName,
                                parentId: dataId,
                                groupType: data.groupType,
                                type: "org"
                            }
                        })
                        url = window.BasicProxy + "/api/commons/school/user/department/staffs";
                        fetch
                        .get({url, params: {
                            sysId: "410",
                            schoolId: sessionStorage.getItem("schoolId"),
                            departmentId: data.id
                        }})
                        .then(res=>res.json())
                        .then((result)=>{
                            if(result.code === "200" && Array.isArray(result.data)){
                                let updateList2 = result.data.map((item)=>{
                                    return {
                                        ...item,
                                        id: item.userId,
                                        name: item.userName,
                                        parentId: dataId,
                                        groupType: data.groupType,
                                        type: "user"
                                    }
                                })
                                let allList = updateList.concat(updateList2);
                                clearMethod(data, allList);
                            }
                        });
                        // setChildList(updateList);
                        // setLoadVisible(false);
                    }
                });
            } else {
                let url = window.BasicProxy + "/api/commons/school/user/department/staffs";
                fetch
                .get({url, params: {
                    sysId: "410",
                    schoolId: sessionStorage.getItem("schoolId"),
                    departmentId: data.id
                }})
                .then(res=>res.json())
                .then((result)=>{
                    if(result.code === "200" && Array.isArray(result.data)){
                        let updateList = result.data.map((item)=>{
                            return {
                                ...item,
                                id: item.userId,
                                parentId: dataId,
                                name: item.userName,
                                type: "user"
                            }
                        })
                        clearMethod(data, updateList);
                        // setChildList(updateList);
                        // setLoadVisible(false);
                    }
                });
            }
            
            
        }
    }
    const clearMethod = (data, arr) => {
        let updateArr = arr.map((item)=>{
            return (item.groupType? item.groupType + "_": "") + item.id
        })
        let deleteList = [data];
        selectList.forEach((item)=>{
            let itemId = (item.groupType? item.groupType + "_": "") + item.id;
            if(updateArr.includes(itemId)){
                deleteList.push(item);
            }
        })
        console.log(deleteList)
        // return;
        selectMethod(deleteList, "", "list");
    }
    //获取历史点击层级数据
    const historyClick = (data, index) => {
        //删除点击的历史记录之后的记录
        let history = JSON.parse(JSON.stringify(historyList));
        history.splice(index+1);
        setHistoryList(history);
        if(!data.id){  //如果id为空，则是取最外层数据
            setGetAll(!getAll);
            return;
        }
        getChildList(data, "historyClick");
    }
    const controlShow = (e) => {
        //列表下拉图标旋转
        if(childVisible) {
            $(e.target).children(".downlogo").css({
                transform: ""
            })
            //收起后需要初始化历史点击记录
            setHistoryList([
                {
                    id: "",
                    name: groupData.name
                }
            ]);
        } else {
            $(e.target).children(".downlogo").css({
                transform: "rotate(180deg)"
            })
        }
        setChildVisible(!childVisible);
    }
    const controlSelect = (value, e) => {
        e && e.stopPropagation();
        e && e.preventDefault();
        //如果是当前被勾选是因为其他父类被选中，就无法取消，需进行提示

        let data = historyList[historyList.length - 1];
        if(selectIdList.includes((data.groupType? data.groupType + "_": "") + data.id)){ 
            //说明是因为父组被选才被选择
            let arr = [];
            arr.push(data);
            let valueId = (value.groupType? value.groupType + "_": "") + value.id;
            childList.forEach((item)=>{
                let itemId = (item.groupType? item.groupType + "_": "") + item.id;
                if(itemId !== valueId){
                    arr.push(item);
                }
            })
            selectMethod(arr, e, "list");
        } else {
            //选择的时候清除所有直接子选项
            if(value.type === "user"){
                selectMethod(value, e);
            } else {
                clearChildList(value);
            }
        }
        
    }
    //选择当前所有选项
    const selectAllChild = (e) => {
        selectMethod(historyList[historyList.length - 1]);
    }
    //选择当前所有
    const selectGroup = (e) => {
        e.stopPropagation();
        let className = $(e.target).attr("class");
        if(className === "checkedlogo"){
            selectMethod(updateChildList, e, "list", "delete");
        } else {
            selectMethod(updateChildList, e, "list", "add");
        }
    }
    useEffect(()=>{   //获取最外层目录数据
        if(!childVisible){
            // return;
        } else {
            setLoadVisible(true);
        }
        let id = groupData.id;
        let list = JSON.parse(JSON.stringify(allChildList));
        if(id === "admin"){
            let url = window.BasicProxy + "/api/commons/school/identity/list";
            fetch
            .get({url, params: {
                schoolId: sessionStorage.getItem("schoolId"),
                userType: 0
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            count: item.count || item.userCount,
                            id: item.identityCode,
                            type: "identity",
                            groupType: id,
                            name: item.identityName
                        }
                    })
                    list.push({
                        type: "all_identity",
                        list: updateList
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            })
        }
        if(id === "tea"){
            let url = window.BasicProxy + "/api/commons/school/group/list";
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                schoolId: sessionStorage.getItem("schoolId"),
                collegeId: ""
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            count: item.count,
                            id: item.subjectId || item.collegeId,
                            type: "group",
                            groupType: id,
                            name: (item.subjectName || item.groupName) + (sessionStorage.getItem("schoolType") == 1? "教学组": "教研组")
                        }
                    })
                    list.push({
                        type: "all_tea",
                        list: updateList
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            })
        }
        if(id === "stu" || id === "parent"){
            let url = window.BasicProxy + "/api/commons/school/grade/list";
            fetch
            .get({url, params: {
                schoolType: sessionStorage.getItem("schoolType"),
                schoolId: sessionStorage.getItem("schoolId"),
                sysId: _sysId
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            count: item.count || item.classCount,
                            id: item.gradeId,
                            type: "grade",
                            groupType: id,
                            name: item.gradeName
                        }
                    })
                    list.push({
                        type: "all_grade",
                        list: updateList
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            })
        }
        if(id === "org"){
            let url = window.BasicProxy + "/api/commons/school/department/list";
            fetch
            .get({url, params: {
                sysId: "410",
                departmentId: "",
                schoolId: sessionStorage.getItem("schoolId")
            }})
            .then(res=>res.json())
            .then((result)=>{
                if(result.code === "200" && Array.isArray(result.data)){
                    let updateList = result.data.map((item)=>{
                        return {
                            ...item,
                            id: item.departmentId,
                            type: "org",
                            groupType: id,
                            name: item.departmentName
                        }
                    })
                    list.push({
                        type: "all_org",
                        list: updateList
                    })
                    setChildList(updateList);
                    setLoadVisible(false);
                }
            })
        }
    }, [childVisible, getAll]);

    useEffect(()=>{   //如果父级勾选了则子列表勾中全选
        let data = historyList[historyList.length - 1];
        if(!data){
            return;
        }
        if(selectIdList.includes((data.groupType? data.groupType + "_": "") + data.id)){
            setSelectAll(true);
        } else {
            setSelectAll(false);
        }
    }, [selectList]);
  
    useEffect(()=>{  //用于判断当前列表各个选择状态
        let list = JSON.parse(JSON.stringify(childList));
        let groupCount = 0;
        list.forEach((item)=>{
            let sign = [];  // 0未选，1半选，2全选
            let count = 0;
            let id = item.id;
            let itemGradeId = item.gradeId;
            let itemClassId = item.classId;
            let itemSubjectIds = item.subjectIds;
            let itemIdentityCode = item.identityCode;
            let itemDepartId = item.departmentId;
            let itemFullId = item.fullPathId;
            let itemParentId = item.parentId && item.parentId.replace("org_", "");
            selectList.forEach((child)=>{
                let chilId = child.id;
                let gradeId = child.gradeId;
                let classId = child.classId;
                let subjectIds = child.subjectIds;
                let identityCode = child.identityCode;
                let departId = child.departmentId;
                let fullId = child.fullPathId;
                let parentId = child.parentId && child.parentId.replace("org_", "");
                
                if(child.groupType !== item.groupType){
                    //搜索出来的用户没有groupType，所以需要放开限制额外判断
                    if(child.type === "user" && id === chilId){
                        sign.push(2);
                    }
                    return;
                }
                if(chilId === id){
                    groupCount++;
                }
                if(chilId === itemDepartId || 
                    chilId === itemIdentityCode || 
                    chilId === itemClassId || 
                    chilId === itemGradeId || 
                    chilId === itemParentId ||
                    (itemSubjectIds && itemSubjectIds.indexOf(chilId) !== -1) ||
                    (item.departmentId && child.departmentId && itemFullId && itemFullId.indexOf(chilId) !== -1)){
                    sign.push(2);
                }
                if(identityCode === id || 
                    departId === id || 
                    classId === id || 
                    gradeId === id || 
                    parentId === id ||
                    (subjectIds && subjectIds.indexOf(id) !== -1) ||
                    (item.departmentId && fullId && fullId.indexOf(id) !== -1)){
                    sign.push(1);
                    count++;
                }
                if(chilId === id){
                    sign.push(2);
                }
            })
            if(count && (count == item.count || count == item.childCount)){
                sign.push(2);
            }
            item.check = Math.max(...sign);
        })
        if(groupCount && groupCount === list.length){
            setSelectAll(2);
        } else if(groupCount){
            setSelectAll(1);
        } else {
            setSelectAll(0);
        }
        setUpdateChildList(list);
    }, [selectList, childList]);
    return (
        <div className={`group_one`}>
            {
                
            }
            <span className="control_container" onClick={controlShow}>
                <i className={
                    selectAll === 2?
                    "checkedlogo":
                    selectAll === 1?
                    "helflogo":
                    "checklogo"
                } onClick={selectGroup}></i>
                {groupData.name}
                <i className="downlogo"></i>
            </span>
            <Loading 
            opacity={false} 
            // wrapperClassName={`collect_load ${childVisible? "": "none"}`} 
            spinning={loadVisible} tip="数据加载中...">
            <ul className={`child_list ${childVisible? "": "none"}`}>
                {
                    historyList.length > 1?
                    <div className="history_list">
                    {
                        historyList.map((item, index)=>{
                            return (
                                <span className="history_one" key={index} onClick={
                                    index !== historyList.length - 1?
                                    ()=>historyClick(item, index):
                                    null
                                }>
                                    {item.name}
                                </span>
                            )
                        })
                    }
                    </div>:
                    ""
                }
                {/* {
                    childList[0] && childList[0].userId?
                    <div className="all_container">
                        <i className={selectAll? "checkedlogo": "checklogo"} onClick={selectAllChild}></i>
                        全选
                    </div>:
                    ""
                } */}
                {
                    updateChildList.length > 0?
                    updateChildList.map((item, index)=>{
                        return (
                            <li 
                            className="child_one" 
                            key={index} 
                            onClick={(e)=>controlSelect(item, e)}
                            // onClick={(e)=>getChildList(item, "", e)}
                            style={{
                                cursor: (item.userId? "default": "")
                            }}
                            title={item.name}>
                                <i className={
                                    item.check === 2?
                                    "checkedlogo":
                                    item.check === 1?
                                    "helflogo":
                                    "checklogo"
                                    // selectIdList.includes((item.groupType? item.groupType + "_": "") + item.id) || 
                                    // selectIdList.includes((historyList[historyList.length - 1].groupType? historyList[historyList.length - 1].groupType + "_": "") + historyList[historyList.length - 1].id)? 
                                    // "checkedlogo": 
                                    // "checklogo"
                                } onClick={(e)=>controlSelect(item, e)}></i>
                                {item.name}
                                {
                                    item.userId?
                                    <span style={{color: "#999"}}>({item.userId})</span>:
                                    <span className="next-floor" onClick={(e)=>getChildList(item, "", e)}><i className="leftlogo"></i>下级</span>
                                }
                            </li>
                        )
                    }):
                    <p className="group_empty">该分组暂无成员</p>
                }
            </ul>
            </Loading>
        </div>
    )
}

export default GroupList;